<!-- 车队编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="640"
    :model-value="modelValue"
    :title="title"
    @update:modelValue="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="利润要求" prop="insurance_remark">
        {{ props.data.reg_date }}注册，{{ props.data.age }}年车，利润要求{{
          props.data.profit
        }}
      </el-form-item>
      <el-form-item label="报价要求" prop="remark">
        <el-input v-model="form.remark" :rows="5" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import { useFormData } from '@/utils/use-form-data';
  import { createPlan } from '@/api/company';
  const emit = defineEmits(['done', 'update:modelValue']);

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object,
    action: {
      type: String,
      default: 'offer'
    }
  });

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);
  const title = ref('');

  /** 表单数据 */
  const [form] = useFormData({
    id: 0,
    remark: '',
    action: '',
    company: '',
    plate_number: ''
  });

  /** 表单验证规则 */
  const rules = reactive({
    remark: [
      {
        required: true,
        message: '请填写报价要求',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });

  /** 保存编辑 */
  const save = () => {
    console.log(form);
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      loading.value = true;
      createPlan(form)
        .then(() => {
          loading.value = false;
          EleMessage.success('操作成功');
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          EleMessage.error(e.message);
        });
    });
  };

  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        if (props.action == 'offer') {
          title.value = '提交' + props.data.plate_number + '的报价申请';
        }

        if (props.action == 'reoffer') {
          title.value = '重新提交' + props.data.plate_number + '的报价申请';
        }
        form.id = props.data.id;
        form.remark = '';
        form.action = props.action;
        form.company = props.data.company;
        form.plate_number = props.data.plate_number;
      } else {
        formRef.value?.clearValidate?.();
      }
    }
  );
</script>
